﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RAD.LightOne;
using RAD.LightOne.Data;

namespace RAD.LightOne.Tester
{
    [DBTable("nodes")]
    [Id("meu_id")]
    public class Node : MyObject<Node>, ISave<Node>
    {
        [DBField("name")]
        public string Name { get; set; }
        [DBField("position")]
        public string Position { get; set; }
        [DBField("parent")]
        public Node Parent { get; set; }

        public new void Save()
        {
            base.Save();
        }

        public static Node[] FindByParent(Node parent)
        {
            return Node.FindBySql("select meu_id, class_name from nodes where parent={0}", parent);
        }

        protected override void OnSaving(System.Data.IDbTransaction trx)
        {
            base.OnSaving(trx);

            if (this.Parent != null && this.Parent.Id == Guid.Empty)
            {
                this.Parent.Save(trx);
            }

            //pegando a posição a partir do banco
            DBEngine dbe = DBEngine.GetInstance(trx);
            string position = Convert.ToString(dbe.ExecuteScalar("select isnull(max(position),'0') + 1 from nodes where ({0} is not null and parent = {0}) or {0} is null", this.Parent));

            this.Position = this.Parent == null ? position.ToString() : string.Format("{0}.{1}", this.Parent.Position, position);

            dbe.ExecuteNonQuery("update nodes set position = '{0}' + substring(position,0,len({0})) where parent = {1}", this.Position, this);
        }

        public new void Save(System.Data.IDbTransaction trx)
        {
            base.Save(trx);
        }

        
    }
}
